package com.baijia.web.extractor;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

public class DessionCookieCleaner {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private String cookieName;
    private String cookieDomain;
    private String cookiePath = "/";

    public void removeCookie(HttpServletResponse response) {
        Assert.notNull(response, "HttpServletResponse must not be null");
        for (String domain : getCookieDomains()) {
            Cookie cookie = createCookie("", domain);
            cookie.setMaxAge(0);
            logger.info("Clear dession cookie {}", ToStringBuilder.reflectionToString(cookie));
            response.addCookie(cookie);
        }

    }

    protected Cookie createCookie(String cookieValue, String domain) {
        Cookie cookie = new Cookie(getCookieName(), cookieValue);
        if (StringUtils.isNotBlank(domain)) {
            cookie.setDomain(domain);
        } else if (getCookieDomain() != null) {
            cookie.setDomain(getCookieDomain());
        }
        cookie.setPath(getCookiePath());
        return cookie;
    }

    public String getCookieName() {

        return cookieName;
    }

    public void setCookieName(String cookieName) {

        this.cookieName = cookieName;
    }

    public String[] getCookieDomains() {
        if (StringUtils.isNotBlank(cookieDomain)) {
            return cookieDomain.split(",");
        } else {
            return new String[] {};
        }
    }

    public String getCookieDomain() {

        return cookieDomain;
    }

    public void setCookieDomain(String cookieDomain) {

        this.cookieDomain = cookieDomain;
    }

    public String getCookiePath() {

        return cookiePath;
    }

    public void setCookiePath(String cookiePath) {

        this.cookiePath = cookiePath;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
